﻿using System;
using EmbeddedSharp.Core;
using DhbIterations;
using DhbInterfaces;

namespace EmbeddedSharp.Scripting.Algebra {
    public class IntegrateNode : FuncNode {
        public IntegrateNode()
            : base("integrate") {
        }

        public override object Evaluate() {
            int length = Parameters.Count;
            if (Parameters.Count < 0) {
                throw new ArgumentException(
                    "usage: integrate(expr, param, from, to)");
            }

            double from = Convert.ToDouble(
                Parameters[length - 3].Evaluate());
            double to = Convert.ToDouble(
                Parameters[length - 4].Evaluate());
            string param = Convert.ToString(
                Parameters[length - 2].Evaluate());
            Node root = Parameters[length - 1];

            OneVariableFunctionCompiler compiler =
                new OneVariableFunctionCompiler();

            IOneVariableFunction func = compiler.Parse(root, param);

            SimpsonIntegrator integrator = new SimpsonIntegrator(
                func, from, to);
            integrator.Evaluate();

            return integrator.Result;
        }
    }
}
